package com.kingsoft.dc.khaos.extender.meta.utils;

import com.kingsoft.dc.khaos.extender.meta.api.AuthRequest;
import com.ksyun.auth.client.AuthenticationHelper;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    private static String APPLICATION_JSON = "application/json";
    private static String DEFAULT_CHARSET = "UTF-8";

    /**
     * 执行get请求,200返回响应内容，其他状态码返回null
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String doGet(String url, Map<String, String> headers) {
        // 创建httpClient对象
        CloseableHttpResponse response = null;
        String result = null;
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url);
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                logger.error("http request error,statusCode is {}", response.getStatusLine().getStatusCode());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            logger.info("http request end......");
//            logger.info("http request url:==>{}", url);
//            logger.info("http response result:==>{}", result);
        }
        return result;
    }

    public static String doPost(String url, Map<String, String> headers, String params) {
        logger.info("http request start......");
        logger.info("http request url:==>{}", url);
        logger.info("http request params:==>{}", params);
        // 创建httpClient对象
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            StringEntity entity = new StringEntity(params);
            entity.setContentType(APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                logger.error("http request fail, status={}, url={}, params={}", response.getStatusLine().getStatusCode(), url, params);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String doPost(String url, Map<String, String> headers, String params, String charset) {
        logger.info("http request start......");
        logger.info("http request url:==>{}", url);
        logger.info("http request params:==>{}", params);
        // 创建httpClient对象
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            StringEntity entity = new StringEntity(params);
            if (charset != null) {
                entity = new StringEntity(params, DEFAULT_CHARSET);
            }
            entity.setContentType(APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                logger.error("http request fail, status={}, url={}, params={}", response.getStatusLine().getStatusCode(), url, params);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
